package ar.edu.unrn.lia.dao.impl;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.inject.Named;
import javax.persistence.NoResultException;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import ar.edu.unrn.lia.dao.UserDAO;
import ar.edu.unrn.lia.generic.GenericDaoJpaImpl;
import ar.edu.unrn.lia.model.User;

//@Repository(value = "userDao")
@Named("userDao")
public class UserDAOImpl extends GenericDaoJpaImpl<User, Long> implements
		UserDAO, Serializable {

	public Predicate[] getSearchPredicates(Root<User> root,
			Map<String, String> filters) {

		CriteriaBuilder builder = this.entityManager.getCriteriaBuilder();
		List<Predicate> predicatesList = new ArrayList<Predicate>();
		root.alias("entity");

		String username = filters.get("username");
		if (username != null && !"".equals(username)) {
			predicatesList.add(builder.like(root.<String> get("username"),
					'%' + username + '%'));
		}
		String nombre = filters.get("firstName");
		if (nombre != null && !"".equals(nombre)) {
			predicatesList.add(builder.like(root.<String> get("firstName"),
					'%' + nombre + '%'));
		}

		String role = filters.get("role.description");
		if (role != null && !"".equals(role)) {
			predicatesList.add(builder.like(root.get("role")
					.<String> get("description"), '%' + role + '%'));
		}

		return predicatesList.toArray(new Predicate[predicatesList.size()]);
	}
	
	@Override
	public User getEntityByUsername(String username) throws NoResultException {
		
		Query query = this.entityManager.createQuery("from User u where u.username = :username");
		query.setParameter("username", username);
		
		return (User) query.getSingleResult();
	}


}